/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.googlecode.datawander;

import com.googlecode.datawander.connectors.MyRelationalDataBaseException;
import com.googlecode.datawander.connectors.OracleConnector;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.logging.Level;
import oracle.jdbc.OracleConnection;
import org.apache.log4j.Logger;

/**
 *
 * @author Marcin Stachniuk
 */
public class SqlCommandExecutor {

    

    public void executeCommandFromFile(String filename) throws Exception {
        try {
            File file = new File(filename);
            int length = (int)file.length();

            BufferedReader fileReader = new BufferedReader(
                    new FileReader(filename));

            char [] buff = new char [length];

            fileReader.read(buff);

            String text = new String(buff);

            String [] commands = text.split(";");

            Connection conn = OracleConnector.getConnection();

            for(String c : commands) {
                executeCommand(conn, c.trim());
            }

            conn.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }


    }

    private void executeCommand(Connection conn, String command) {
        if(command == null || command.length() == 0) {
            System.out.println("Empty command");
            return;
        }
        try {
            PreparedStatement stmt = conn.prepareStatement(command);
            stmt.execute();
            stmt.close();
            System.out.println("Ok Command: "+command);
        } catch (Exception ex) {
            System.out.println("Error with command: "+command+" \nerror: "+ex.getMessage());
        }
    }
}
